<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="生成一个记录标识的需求，例如： 消息标识：message-id 订单标识：order-id 帖子标识：tiezi-id  这个记录标识往往就是数据库中的唯一主键，数据库上会建立聚集索引（cluster index），即在物理存储上以这个字段排序。">
<meta property="og:type" content="article">
<meta property="og:title" content="如何高效生成趋势有序的全局唯一ID？">
<meta property="og:url" content="http://changyuan.github.io/2015/12/04/gen-id-way/index.html">
<meta property="og:site_name" content="Chang Crazy&#39;s Blog">
<meta property="og:description" content="生成一个记录标识的需求，例如： 消息标识：message-id 订单标识：order-id 帖子标识：tiezi-id  这个记录标识往往就是数据库中的唯一主键，数据库上会建立聚集索引（cluster index），即在物理存储上以这个字段排序。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://changyuan.github.io/images/technology/gen-id.png">
<meta property="og:image" content="http://changyuan.github.io/images/technology/gen-id2.png">
<meta property="og:image" content="http://changyuan.github.io/images/technology/gen-id3.png">
<meta property="og:image" content="http://changyuan.github.io/images/technology/snowflake-64bit.jpg">
<meta property="og:updated_time" content="2015-12-04T05:57:12.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="如何高效生成趋势有序的全局唯一ID？">
<meta name="twitter:description" content="生成一个记录标识的需求，例如： 消息标识：message-id 订单标识：order-id 帖子标识：tiezi-id  这个记录标识往往就是数据库中的唯一主键，数据库上会建立聚集索引（cluster index），即在物理存储上以这个字段排序。">
<meta name="twitter:image" content="http://changyuan.github.io/images/technology/gen-id.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://changyuan.github.io/2015/12/04/gen-id-way/">





  <title>如何高效生成趋势有序的全局唯一ID？ | Chang Crazy's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chang Crazy's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">升级自己的操作系统</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-schedule">
          <a href="/schedule/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br>
            
            日程表
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://changyuan.github.io/2015/12/04/gen-id-way/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="changyuan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chang Crazy's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">如何高效生成趋势有序的全局唯一ID？</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2015-12-04T13:57:12+08:00">
                2015-12-04
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="生成一个记录标识的需求，例如："><a href="#生成一个记录标识的需求，例如：" class="headerlink" title="生成一个记录标识的需求，例如："></a>生成一个记录标识的需求，例如：</h1><ol>
<li>消息标识：message-id</li>
<li>订单标识：order-id</li>
<li>帖子标识：tiezi-id</li>
</ol>
<p>这个记录标识往往就是数据库中的唯一主键，数据库上会建立聚集索引（<code>cluster index</code>），即在物理存储上以这个字段排序。</p>
<a id="more"></a>
<p>这个记录标识上的查询，往往又有分页或者排序的业务需求，例如：</p>
<ul>
<li>拉取最新的一页消息：selectmessage-id/ order by time/ limit 100</li>
<li>拉取最新的一页订单：selectorder-id/ order by time/ limit 100</li>
<li>拉取最新的一页帖子：selecttiezi-id/ order by time/ limit 100<br>所以往往要有一个time字段，并且在time字段上建立普通索引（non-cluster index）。</li>
</ul>
<p>我们都知道普通索引存储的是实际记录的指针，其访问效率会比聚集索引慢，如果记录标识在生成时能够基本按照时间有序，则可以省去这个time字段的索引查询：<br><code>select message-id/ (order by message-id)/limit 100</code><br>再次强调，能这么做的前提是，message-id的生成基本是趋势时间递增的。</p>
<p>两大核心需求：</p>
<ol>
<li>全局唯一</li>
<li>趋势有序</li>
</ol>
<h2 id="常见方法、不足、优化"><a href="#常见方法、不足、优化" class="headerlink" title="常见方法、不足、优化"></a>常见方法、不足、优化</h2><h3 id="1-用数据库的-auto-increment"><a href="#1-用数据库的-auto-increment" class="headerlink" title="1.用数据库的 auto_increment"></a>1.用数据库的 auto_increment</h3><h4 id="优点："><a href="#优点：" class="headerlink" title="优点："></a>优点：</h4><ol>
<li>简单，使用数据库已有的功能</li>
<li>能够保证唯一性</li>
<li>能够保证递增性</li>
<li>步长固定</li>
</ol>
<h4 id="缺点："><a href="#缺点：" class="headerlink" title="缺点："></a>缺点：</h4><ol>
<li>可用性难以保证：数据库常见架构是一主多从+读写分离，生成自增ID是写请求，主库挂了就玩不转了</li>
<li>扩展性差，性能有上限：因为写入是单点，数据库主库的写性能决定ID的生成性能上限，并且难以扩展</li>
</ol>
<h4 id="改进方法："><a href="#改进方法：" class="headerlink" title="改进方法："></a><strong>改进方法</strong>：</h4><ol>
<li>增加主库，避免写入单点</li>
<li>数据水平切分，保证各主库生成的ID不重复</li>
</ol>
<p><img src="/images/technology/gen-id.png" alt="pic"></p>
<p>如上图所述，由1个写库变成3个写库，每个写库设置不同的auto_increment初始值，以及相同的增长步长，以保证每个数据库生成的ID是不同的（上图中库0生成0,3,6,9…，库1生成1,4,7,10，库2生成2,5,8,11…）, 改进后的架构保证了可用性。</p>
<p><strong>缺点是</strong>：</p>
<ol>
<li>丧失了ID生成的“绝对递增性”：先访问库0生成0,3，再访问库1生成1，可能导致在非常短的时间内，ID生成不是绝对递增的（这个问题不大，我们的目标是趋势递增，不是绝对递增）</li>
<li>数据库的写压力依然很大，每次生成ID都要访问数据库<br>为了解决上述两个问题，引出了第二个常见的方案</li>
</ol>
<h3 id="单点批量ID生成服务"><a href="#单点批量ID生成服务" class="headerlink" title="单点批量ID生成服务"></a>单点批量ID生成服务</h3><p>分布式系统之所以难，很重要的原因之一是“没有一个全局时钟，难以保证绝对的时序”，要想保证绝对的时序，还是只能使用单点服务，用本地时钟保证“绝对时序”。数据库写压力大，是因为每次生成ID都访问了数据库，可以使用批量的方式降低数据库写压力。</p>
<p><img src="/images/technology/gen-id2.png" alt="pic"></p>
<p>如上图所述，数据库使用双master保证可用性，数据库中只存储当前ID的最大值，例如0。ID生成服务假设每次批量拉取6个ID，服务访问数据库，将当前ID的最大值修改为5，这样应用访问ID生成服务索要ID，ID生成服务不需要每次访问数据库，就能依次派发0,1,2,3,4,5这些ID了，当ID发完后，再将ID的最大值修改为11，就能再次派发6,7,8,9,10,11这些ID了，于是数据库的压力就降低到原来的1/6了。</p>
<h4 id="优点：-1"><a href="#优点：-1" class="headerlink" title="优点："></a>优点：</h4><ol>
<li>保证了ID生成的绝对递增有序</li>
<li>大大的降低了数据库的压力，ID生成可以做到每秒生成几万几十万个</li>
</ol>
<h4 id="缺点：-1"><a href="#缺点：-1" class="headerlink" title="缺点："></a>缺点：</h4><ol>
<li>服务仍然是单点</li>
<li>如果服务挂了，服务重启起来之后，继续生成ID可能会不连续，中间出现空洞（服务内存是保存着0,1,2,3,4,5，数据库中max-id是5，分配到3时，服务重启了，下次会从6开始分配，4和5就成了空洞，不过这个问题也不大）</li>
<li>虽然每秒可以生成几万几十万个ID，但毕竟还是有性能上限，无法进行水平扩展</li>
</ol>
<h4 id="改进方法：-1"><a href="#改进方法：-1" class="headerlink" title="改进方法："></a><strong>改进方法</strong>：</h4><p><strong> 单点服务的常用高可用优化方案是“备用服务”，也叫“影子服务”，</strong> 所以我们能用以下方法优化上述缺点（1）：</p>
<p><img src="/images/technology/gen-id3.png" alt="pic"><br>如上图，对外提供的服务是主服务，有一个影子服务时刻处于备用状态，当主服务挂了的时候影子服务顶上。这个切换的过程对调用方是透明的，可以自动完成，常用的技术是vip+keepalived，具体就不在这里展开。</p>
<h3 id="uuid"><a href="#uuid" class="headerlink" title="uuid"></a>uuid</h3><p>上述方案来生成ID，虽然性能大增，但由于是单点系统，总还是存在性能上限的。同时，上述两种方案，不管是数据库还是服务来生成ID，业务方Application都需要进行一次远程调用，比较耗时。有没有一种本地生成ID的方法，即高性能，又时延低呢？</p>
<p>uuid是一种常见的方案：<code>string ID = GenUUID();</code></p>
<h4 id="优点：-2"><a href="#优点：-2" class="headerlink" title="优点："></a>优点：</h4><ol>
<li>本地生成ID，不需要进行远程调用，时延低</li>
<li>扩展性好，基本可以认为没有性能上限</li>
</ol>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// com_create_guid()</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">guid</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (function_exists(<span class="string">'com_create_guid'</span>))&#123;</span><br><span class="line">        <span class="keyword">return</span> com_create_guid();</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        mt_srand((double)microtime()*<span class="number">10000</span>);<span class="comment">//optional for php 4.2.0 and up.</span></span><br><span class="line">        $charid = strtoupper(md5(uniqid(rand(), <span class="keyword">true</span>)));</span><br><span class="line">        $hyphen = chr(<span class="number">45</span>);<span class="comment">// "-"</span></span><br><span class="line">        $uuid = chr(<span class="number">123</span>)<span class="comment">// "&#123;"</span></span><br><span class="line">                .substr($charid, <span class="number">0</span>, <span class="number">8</span>).$hyphen</span><br><span class="line">                .substr($charid, <span class="number">8</span>, <span class="number">4</span>).$hyphen</span><br><span class="line">                .substr($charid,<span class="number">12</span>, <span class="number">4</span>).$hyphen</span><br><span class="line">                .substr($charid,<span class="number">16</span>, <span class="number">4</span>).$hyphen</span><br><span class="line">                .substr($charid,<span class="number">20</span>,<span class="number">12</span>)</span><br><span class="line">                .chr(<span class="number">125</span>);<span class="comment">// "&#125;"</span></span><br><span class="line">        <span class="keyword">return</span> $uuid;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">echo</span> guid();</span><br></pre></td></tr></table></figure>
<h4 id="缺点：-2"><a href="#缺点：-2" class="headerlink" title="缺点："></a>缺点：</h4><ol>
<li>无法保证趋势递增</li>
<li>uuid过长，往往用字符串表示，作为主键建立索引查询效率低，常见优化方案为“转化为两个uint64整数存储”或者“折半存储”（折半后不能保证唯一性）</li>
</ol>
<h3 id="取当前毫秒数"><a href="#取当前毫秒数" class="headerlink" title="取当前毫秒数"></a>取当前毫秒数</h3><p>uuid是一个本地算法，生成性能高，但无法保证趋势递增，且作为字符串ID检索效率低，有没有一种能保证递增的本地算法呢？<br>取当前毫秒数是一种常见方案：<code>uint64 ID = GenTimeMS();</code></p>
<h4 id="优点：-3"><a href="#优点：-3" class="headerlink" title="优点："></a>优点：</h4><ol>
<li>本地生成ID，不需要进行远程调用，时延低</li>
<li>生成的ID趋势递增</li>
<li>生成的ID是整数，建立索引后查询效率高</li>
</ol>
<h4 id="缺点：-3"><a href="#缺点：-3" class="headerlink" title="缺点："></a>缺点：</h4><p>（1）如果并发量超过1000，会生成重复的ID, 当然，使用微秒可以降低冲突概率，但每秒最多只能生成1000000个ID，再多的话就一定会冲突了，所以使用微秒并不从根本上解决问题。</p>
<h3 id="类snowflake算法-snowflake"><a href="#类snowflake算法-snowflake" class="headerlink" title="类snowflake算法 snowflake"></a>类snowflake算法 <a href="https://github.com/twitter/snowflake" target="_blank" rel="noopener">snowflake</a></h3><p>snowflake是twitter开源的分布式ID生成算法.</p>
<p>0—0000000000 0000000000 0000000000 0000000000 0 — 00000 —00000 —000000000000</p>
<p><img src="/images/technology/snowflake-64bit.jpg" alt="pic"></p>
<p>“41bit的时间戳可以支持该算法使用年限：(时间差的毫秒数)”, (1L &lt;&lt; 41) / (3600L <em> 24 </em> 365 * 1000.0)，其中1L为长整形，位移41位为 ： 2199023255552 /31536000000=69.73057000101471<br>“10bit的工作机器id数量：{0}”, (1L &lt;&lt; 10) - 1  为： 1023<br>“12bit序列id数量：{0}”, (1L &lt;&lt; 12) - 1 为：4095</p>
<p>一个long型的ID，使用其中<code>41bit</code>作为毫秒数，<code>10bit</code>作为机器编号，<code>12bit</code>作为毫秒内序列号。这个算法<strong>单机每秒</strong>内理论上最多可以生成<code>1000 * (2^12-1) 或 1000 * ((1 &lt;&lt; 12)- 1)</code>，也就是4096000个ID。</p>
<p>借鉴snowflake的思想，结合各公司的业务逻辑和并发量，可以实现自己的分布式ID生成算法。</p>
<p>举例，假设某公司ID生成器服务的需求如下：</p>
<ol>
<li>单机高峰并发量小于1W，预计未来5年单机高峰并发量小于10W</li>
<li>有2个机房，预计未来5年机房数量小于4个</li>
<li>每个机房机器数小于100台</li>
<li>目前有5个业务线有ID生成需求，预计未来业务线数量小于10个</li>
</ol>
<p>分析过程如下：</p>
<ol>
<li>高位取从2016年1月1日到现在的毫秒数（假设系统ID生成器服务在这个时间之后上线），假设系统至少运行10年，那至少需要 <code>10年*365天*24小时*3600秒*1000毫秒=320*10^9</code>，差不多预留39bit给毫秒</li>
<li>每秒的单机高峰并发量小于10W，即平均每毫秒的单机高峰并发量小于100，差不多预留7bit给每毫秒内序列号</li>
<li>5年内机房数小于4个，预留2bit给机房标识</li>
<li>每个机房小于100台机器，预留7bit给每个机房内的服务器标识</li>
<li>业务线小于10个，预留4bit给业务线标识</li>
</ol>
<h4 id="优点：-4"><a href="#优点：-4" class="headerlink" title="优点："></a>优点：</h4><p>这样设计的64bit标识，可以保证：</p>
<ol>
<li>每个业务线、每个机房、每个机器生成的ID都是不同的</li>
<li>同一个机器，每个毫秒内生成的ID都是不同的</li>
<li>同一个机器，同一个毫秒内，以序列号区区分保证生成的ID是不同的</li>
<li>将毫秒数放在最高位，保证生成的ID是趋势递增的</li>
</ol>
<h4 id="缺点：-4"><a href="#缺点：-4" class="headerlink" title="缺点："></a>缺点：</h4><p>（1）由于“没有一个全局时钟”，每台服务器分配的ID是绝对递增的，但从全局看，生成的ID只是趋势递增的（有些服务器的时间早，有些服务器的时间晚）<br>最后一个容易忽略的问题：<br>生成的ID，例如<code>message-id/ order-id/ tiezi-id</code>，在数据量大时往往需要分库分表，这些ID经常作为取模分库分表的依据，为了分库分表后数据均匀，ID生成往往有“取模随机性”的需求，所以我们通常把<strong>每秒内的序列号放在ID的最末位</strong>，保证生成的ID是随机的。<br>又如果，我们在跨毫秒时，序列号总是归0，<strong>会使得序列号为0的ID比较多，导致生成的ID取模后不均匀</strong>。解决方法是，<strong>序列号不是每次都归0，而是归一个0到9的随机数</strong>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Snowflake</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//工作机器id的bit段拆分为前5个bit标记workerid，后5个bit标记datacenterid</span></span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">int</span> WorkerIdBits = <span class="number">5</span>;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">int</span> DatacenterIdBits = <span class="number">5</span>;</span><br><span class="line">    <span class="comment">//序列号bit数</span></span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">int</span> SequenceBits = <span class="number">12</span>;</span><br><span class="line">    <span class="comment">//最大编号限制</span></span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">long</span> MaxWorkerId = -<span class="number">1L</span> ^ (-<span class="number">1L</span> &lt;&lt; WorkerIdBits);</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">long</span> MaxDatacenterId = -<span class="number">1L</span> ^ (-<span class="number">1L</span> &lt;&lt; DatacenterIdBits);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">const</span> <span class="keyword">long</span> SequenceMask = -<span class="number">1L</span> ^ (-<span class="number">1L</span> &lt;&lt; SequenceBits);</span><br><span class="line">    <span class="comment">//位左运算移动量</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">const</span> <span class="keyword">int</span> WorkerIdShift = SequenceBits;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">const</span> <span class="keyword">int</span> DatacenterIdShift = SequenceBits + WorkerIdBits;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">const</span> <span class="keyword">int</span> TimestampLeftShift = SequenceBits + WorkerIdBits + DatacenterIdBits;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//序列号记录</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> _sequence = <span class="number">0L</span>;</span><br><span class="line">    <span class="comment">//时间戳记录</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> _lastTimestamp = -<span class="number">1L</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">long</span> WorkerId &#123; get; <span class="keyword">protected</span> set; &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">long</span> DatacenterId &#123; get; <span class="keyword">protected</span> set; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Snowflake</span><span class="params">(<span class="keyword">long</span> workerId, <span class="keyword">long</span> datacenterId, <span class="keyword">long</span> sequence = <span class="number">0</span>L)</span> </span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        WorkerId = workerId;</span><br><span class="line">        DatacenterId = datacenterId;</span><br><span class="line">        _sequence = sequence;</span><br><span class="line">    </span><br><span class="line">        <span class="comment">// sanity check for workerId</span></span><br><span class="line">        <span class="keyword">if</span> (workerId &gt; MaxWorkerId || workerId &lt; <span class="number">0</span>) </span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ArgumentException( String.Format(<span class="string">"worker Id can't be greater than &#123;0&#125; or less than 0"</span>, MaxWorkerId) );</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (datacenterId &gt; MaxDatacenterId || datacenterId &lt; <span class="number">0</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ArgumentException( String.Format(<span class="string">"datacenter Id can't be greater than &#123;0&#125; or less than 0"</span>, MaxDatacenterId));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/// &lt;summary&gt;</span></span><br><span class="line">    <span class="comment">/// 格林时间戳</span></span><br><span class="line">    <span class="comment">/// &lt;/summary&gt;</span></span><br><span class="line">    <span class="comment">/// &lt;returns&gt;&lt;/returns&gt;</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">TimeGen</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        DateTime Jan1st1970 = <span class="keyword">new</span> DateTime(<span class="number">1970</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, DateTimeKind.Utc);<span class="comment">//</span></span><br><span class="line">        <span class="keyword">return</span> (<span class="keyword">long</span>)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    readonly object _lock = <span class="keyword">new</span> Object();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> virtual <span class="keyword">long</span> <span class="title">NextId</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        lock (_lock)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">var</span> timestamp = TimeGen();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (timestamp &lt; _lastTimestamp)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> InvalidSystemClock(String.Format(</span><br><span class="line">                    <span class="string">"发现最新时间戳少&#123;0&#125;毫秒的异常"</span>, _lastTimestamp - timestamp));</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (_lastTimestamp == timestamp)</span><br><span class="line">            &#123;</span><br><span class="line">                _sequence = (_sequence + <span class="number">1</span>) &amp; SequenceMask;</span><br><span class="line">                <span class="keyword">if</span> (_sequence == <span class="number">0</span>)</span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="comment">//序列号超过限制，重新取时间戳</span></span><br><span class="line">                    timestamp = TilNextMillis(_lastTimestamp);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span></span><br><span class="line">            &#123;</span><br><span class="line">                _sequence = <span class="number">0</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            _lastTimestamp = timestamp;</span><br><span class="line">            <span class="comment">//snowflake算法</span></span><br><span class="line">            <span class="keyword">var</span> id = (timestamp &lt;&lt; TimestampLeftShift) |</span><br><span class="line">                     (DatacenterId &lt;&lt; DatacenterIdShift) |</span><br><span class="line">                     (WorkerId &lt;&lt; WorkerIdShift) | _sequence;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> id;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/// &lt;summary&gt;</span></span><br><span class="line">    <span class="comment">/// 重新取时间戳</span></span><br><span class="line">    <span class="comment">/// &lt;/summary&gt;</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> virtual <span class="keyword">long</span> <span class="title">TilNextMillis</span><span class="params">(<span class="keyword">long</span> lastTimestamp)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> timestamp = TimeGen();</span><br><span class="line">        <span class="keyword">while</span> (timestamp &lt;= lastTimestamp)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="comment">//新的时间戳要大于旧的时间戳，才算作有效时间戳</span></span><br><span class="line">            timestamp = TimeGen();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> timestamp;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>分享即是成长</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat-reward-image.png" alt="changyuan 微信支付">
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    changyuan
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://changyuan.github.io/2015/12/04/gen-id-way/" title="如何高效生成趋势有序的全局唯一ID？">http://changyuan.github.io/2015/12/04/gen-id-way/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2015/11/14/nodejs/" rel="next" title="nodejs 基础">
                <i class="fa fa-chevron-left"></i> nodejs 基础
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/01/28/ganji-design-msyql-rule/" rel="prev" title="【转】赶集Mysql军规">
                【转】赶集Mysql军规 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="changyuan">
            
              <p class="site-author-name" itemprop="name">changyuan</p>
              <p class="site-description motion-element" itemprop="description">不断升级自己的操作系统</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">69</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">26</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/changyuan" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-fab fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/changocean1" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-fab fa-twitter"></i>Twitter</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://weibo.com/changyuan2011" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-fab fa-weibo"></i>Weibo</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.douban.com/people/changyuanyuan" target="_blank" title="Zhihu">
                      
                        <i class="fa fa-fw fa-fab fa-quora"></i>Zhihu</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://weibo.com/changyuan2011" title="Weibo" target="_blank">Weibo</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/changyuan" title="GitHub" target="_blank">GitHub</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#生成一个记录标识的需求，例如："><span class="nav-number">1.</span> <span class="nav-text">生成一个记录标识的需求，例如：</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#常见方法、不足、优化"><span class="nav-number">1.1.</span> <span class="nav-text">常见方法、不足、优化</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-用数据库的-auto-increment"><span class="nav-number">1.1.1.</span> <span class="nav-text">1.用数据库的 auto_increment</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#优点："><span class="nav-number">1.1.1.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#缺点："><span class="nav-number">1.1.1.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#改进方法："><span class="nav-number">1.1.1.3.</span> <span class="nav-text">改进方法：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#单点批量ID生成服务"><span class="nav-number">1.1.2.</span> <span class="nav-text">单点批量ID生成服务</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#优点：-1"><span class="nav-number">1.1.2.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#缺点：-1"><span class="nav-number">1.1.2.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#改进方法：-1"><span class="nav-number">1.1.2.3.</span> <span class="nav-text">改进方法：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#uuid"><span class="nav-number">1.1.3.</span> <span class="nav-text">uuid</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#优点：-2"><span class="nav-number">1.1.3.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#缺点：-2"><span class="nav-number">1.1.3.2.</span> <span class="nav-text">缺点：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#取当前毫秒数"><span class="nav-number">1.1.4.</span> <span class="nav-text">取当前毫秒数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#优点：-3"><span class="nav-number">1.1.4.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#缺点：-3"><span class="nav-number">1.1.4.2.</span> <span class="nav-text">缺点：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#类snowflake算法-snowflake"><span class="nav-number">1.1.5.</span> <span class="nav-text">类snowflake算法 snowflake</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#优点：-4"><span class="nav-number">1.1.5.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#缺点：-4"><span class="nav-number">1.1.5.2.</span> <span class="nav-text">缺点：</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">changyuan</span>

  
</div>









<!-- 网站运行时间的设置 -->
<span id="timeDate">载入天数...</span>
<span id="times">载入时分秒...</span>
<script>
    var now = new Date();
    function createtime() {
        var grt= new Date("08/08/2014 00:00:00");
        now.setTime(now.getTime()+250);
        days = (now - grt ) / 1000 / 60 / 60 / 24; dnum = Math.floor(days);
        hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum); hnum = Math.floor(hours);
        if(String(hnum).length ==1 ){hnum = "0" + hnum;} minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
        mnum = Math.floor(minutes); if(String(mnum).length ==1 ){mnum = "0" + mnum;}
        seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
        snum = Math.round(seconds); if(String(snum).length ==1 ){snum = "0" + snum;}
        document.getElementById("timeDate").innerHTML = "本站已运行 "+dnum+" 天 ";
        document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒.";
    }
setInterval("createtime()",250);
</script>

        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
